<?php

namespace app\health\library;

use think\Hook;
use think\Cache;

/**
 * 短信验证码类
 */
class Sms
{
    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 900;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;

    /**
     * 发送验证码
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码,为空时将自动生成4位数字
     * @param   string $scene  场景
     * @return  boolean|int|string
     */
    public static  function send($mobile, $scene = 'login')
    {
        $code = mt_rand(1000, 9999);
        $data['mobile'] = $mobile;
        $data['content'] = '您的验证码是' . $code;
        $result = SendSms::singleSend($data);
        if ($result['result'] == 0) {
            Cache::rm("sendSmsCodeVerifyNum:" . $scene . ":" . $mobile);
            Cache::set("sendSmsCode:" . $scene . ":" . $mobile, $code, self::$expire);
            return $code;
        } else {
            return false;
        }
    }

    /**
     * 校验验证码
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码
     * @param   string $scene  验证场景
     */
    public static function check($mobile, $code, $scene = 'login')
    {
        $verifyNumKey = "sendSmsCodeVerifyNum:" . $scene . ":" . $mobile;
        $key = "sendSmsCode:" . $scene . ":" . $mobile;
        if (!Cache::has($key)) {
            return '请先发送验证码';
        }
        if (Cache::has($verifyNumKey)) {
            if (Cache::get($verifyNumKey) >= self::$maxCheckNums) {
                return '已达到最大验证次数,请重新获取验证码';
            }
            Cache::set($verifyNumKey, 1, self::$expire);
        } else {
            Cache::inc($verifyNumKey);
        }
        if (Cache::get($key) != $code) {
            return '验证码错误';
        }
        Cache::rm($key);
        return true;
    }
}
